<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
       //微信的token
    private $token = "scunxcb";
    private $wechat = null;
    
    public function __construct() {
         $this->wechat = new \Wechat\Model\WechatReturnMsgModel();
        parent::__construct();     
    }
    
       //检测是否为微信服务器发送
    private function checkSignature(){
        $signature = I("request.signature");
        $timestamp = I('request.timestamp');
        $nonce = I('request.nonce');
        $test = new \Wechat\Model\TestModel();
        $test->create(array('value'=>"$signature|||$timestamp|||$nonce"));
        $test->add();
        $tmpArr = array($this->token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        return ($tmpStr == $signature);
    }
    
        
    //按照消息类型分发请求
    private function router($obj){
        $msgType = trim($obj->MsgType);
        switch ($msgType){
            case 'text':
                $this->receiveText($obj);
                break;
            case 'event':
                $this->receiveEvent($obj);
                break;
            default :
                break;
        }
    }
    
    //文字消息处理
    private function receiveText($obj)
    {
        $this->wechat->returnText($obj,"偷懒中，还没做");
    }

       //事件消息处理
    private function receiveEvent($obj)
    {
        $this->wechat->returnText($obj, "偷懒中。。。");
    }
    

    /**
     * 微信验证
     */  
    public function index(){
        $echoStr = I('get.echostr',"");
        if ($echoStr!=""){
            echo ($this->checkSignature())?$echoStr:"error1";
        }  else {
            $postData = $GLOBALS["HTTP_RAW_POST_DATA"];
            if ($postData!=""){
                $test = new \Wechat\Model\TestModel();                
                $postObj = simplexml_load_string($postData, 'SimpleXMLElement', LIBXML_NOCDATA);
            }else {
                echo "";
            }
        }
    }
    
    
    
    
    
}